﻿using Furion.DependencyInjection;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gear.NoSql.Core.Redis
{
    public interface IRedisFuncProvider
    {
        bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?));

        RedisValue GetStringKey(string key);

        T GetStringKey<T>(string key);

        bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?));
    }

    public class RedisFuncProvider: IRedisFuncProvider, ITransient
    {
        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="value">保存的值</param>
        /// <param name="expiry">过期时间</param>
        public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            return RedisClientSettings.db.StringSet(key, value, expiry);
        }

        /// <summary>
        /// 获取单个key的值
        /// </summary>
        public RedisValue GetStringKey(string key)
        {
            return RedisClientSettings.db.StringGet(key);
        }

        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        public T GetStringKey<T>(string key)
        {
            if (RedisClientSettings.db == null)
            {
                return default;
            }
            var value = RedisClientSettings.db.StringGet(key);
            if (value.IsNullOrEmpty)
            {
                return default;
            }
            return JsonConvert.DeserializeObject<T>(value);
        }

        /// <summary>
        /// 保存一个对象
        /// </summary>
        /// <param name="obj"></param>
        public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
        {
            if (RedisClientSettings.db == null)
            {
                return false;
            }
            string json = JsonConvert.SerializeObject(obj);
            return RedisClientSettings.db.StringSet(key, json, expiry);
        }

    }
}
